package views.fliper
{
	import com.greensock.TweenLite;
	import com.greensock.easing.Cubic;
	import com.greensock.easing.Expo;
	import com.greensock.easing.Linear;
	
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;

	public class FliperView extends Sprite
	{
		
		private var flipPage:FlipPageView;
		private var flipQueue:Vector.<FlipQueueItem>;
		private var processingItem:FlipQueueItem;
		
		private var flipping:Boolean;
		
		private var hSlice:int;
		private var vSlice:int;
		
		private const FLIP_SCALE:Number = 0.85;
		private const ROTATE_DURATION:Number = 0.75;
		
		
		public function FliperView(hSlice:int = 2,vSlice:int = 2)
		{
			this.hSlice = hSlice;
			this.vSlice = vSlice;
			
			initialize();
		}
		
		private function initialize():void
		{
			flipQueue = new Vector.<FlipQueueItem>;
			flipping = false;
			
			flipPage = new FlipPageView(hSlice,vSlice);
			addChild(flipPage);
		}
		
		private function processOver():void
		{
			if(processingItem.callback is Function)
				processingItem.callback.call(null,processingItem.view);
			
			processingItem = null;
			flipping = false;
			processFlipItem();
		}
		
		private function processFlipItem():void
		{
			if(flipping || flipQueue.length <= 0)
				return;
			
			flipPage.reset();
			
			flipping = true;
			processingItem = flipQueue.shift();
			
			var bmData:BitmapData = new BitmapData(processingItem.view.width,processingItem.view.height);
			bmData.draw(processingItem.view);
			flipPage.initialize(bmData);
			
			flipPage.visible = true;
			doFlip();
		}
		
		private function doFlip():void
		{
			flipPage.asix = processingItem.asix;
			if(processingItem.flipType == FlipQueueItem.FLIP_IN)
			{
				flipPage.flipRotation = Math.PI / 2;
				TweenLite.to(flipPage,ROTATE_DURATION,{flipRotation:Math.PI,ease:Cubic.easeOut,onComplete:processOver});
			}else{
				TweenLite.to(flipPage,ROTATE_DURATION,{flipRotation:Math.PI / 2,ease:Cubic.easeIn,onComplete:processOver});				
			}
		}
		
		public function flip(page:DisplayObject,flipType:int = 0,asix:int = 0,callback:Function = null):void
		{
			var item:FlipQueueItem = new FlipQueueItem(page,flipType,asix,callback);
			flipQueue.push(item);
			processFlipItem();
		}
		
		public function reset():void
		{
			TweenLite.killTweensOf(flipPage);
			flipPage.reset();
			flipQueue = new Vector.<FlipQueueItem>;
			flipping = false;
		}
		
	}
}